package com.bs.manager04.utils.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bs.manager04.entity.User;
import com.bs.manager04.utils.RedisUtils;
import com.bs.manager04.utils.TokenUtils;
import com.bs.manager04.utils.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 小姚
 * @pakeageName:com.bs.manager04.utils.security
 * @ClassName:SecurityFilter
 * @Descirption:
 * @data 2022/12/23 1:02
 */
//将过滤器交给spring容器管理
@Component
public class SecurityFilter extends OncePerRequestFilter {

    //注入redis工具类
    @Resource
    RedisUtils utils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      //获取请求消息头数据
        String token = request.getHeader(TokenUtils.TOKEN_NAME);
        if(StringUtils.isBlank(token)){
            filterChain.doFilter(request,response);
            return;
        }
      /*  String subject="";
        try {
            Claims claims = JwtUtil.parseJWT(token);
             subject=claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
       LoginUser loginUser = JSONUtil.toBean(subject, LoginUser.class);*/
        //根据获取到的请求消息头获取登录的用户信息
        LoginUser user =(LoginUser) utils.get("user"+token);
        //判断用户对象是否为空
        if(Objects.isNull(user)){
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken usernamePassword=new UsernamePasswordAuthenticationToken(user,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePassword);
        filterChain.doFilter(request,response);


    }
}
